package cn.xzqwjw.taskmanager.security.handler;

import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义管理员登录失败的错误输出格式，这里是输出成json
 *
 * @author rush
 */
public class LoginFailedJwtHandler implements AuthenticationFailureHandler {

  @Override
  public void onAuthenticationFailure(HttpServletRequest request,
                                      HttpServletResponse response,
                                      AuthenticationException exception) {
    // 回复一个 401 的 Response
    // response.sendError 适用于报错且存在对应的报错页面配置作为输出显示的情况
    // response.setStatus 适用于正常响应的情况，仅仅可以改变响应状态码而已
    // System.out.println("===== LoginFailedJwtHandler 捕获的异常是：" + exception.getMessage());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    // String code = ResponseCodeEnum.BAD_REQUEST.getStatusCode();
    String code = String.valueOf(response.getStatus());
    String message = exception.getMessage();
    // 登录失败，响应返回jwt也是个空值
    ResponseUtil.writeJsonJwt(response, "", ResponseVo.error(code, message));
  }

}
